<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="IP地址" prop="ip">
        <el-input
          v-model="queryParams.ip"
          placeholder="请输入IP地址"
          clearable
          style="width: 160px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="域名" prop="domain">
        <el-input
          v-model="queryParams.domain"
          placeholder="请输入域名"
          clearable
          style="width: 160px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务器ID" prop="serverId">
        <el-input
          v-model="queryParams.serverId"
          placeholder="请输入服务器ID"
          clearable
          style="width: 160px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px;">
          <el-option label="离线" value="0" />
          <el-option label="在线" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:wvpMediaServer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:wvpMediaServer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:wvpMediaServer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:wvpMediaServer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="wvpMediaServerList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="60" />
      <el-table-column label="IP地址" align="center" prop="ip" width="120" show-overflow-tooltip />
      <el-table-column label="域名" align="center" prop="domain" width="150" show-overflow-tooltip />
      <el-table-column label="钩子IP" align="center" prop="hookIp" width="120" show-overflow-tooltip />
      <el-table-column label="SDP IP" align="center" prop="sdpIp" width="120" show-overflow-tooltip />
      <el-table-column label="流媒体IP" align="center" prop="streamIp" width="120" show-overflow-tooltip />
      <el-table-column label="HTTP" align="center" prop="httpPort" width="70" />
      <el-table-column label="HTTPS" align="center" prop="httpSslPort" width="70" />
      <el-table-column label="RTMP" align="center" prop="rtmpPort" width="70" />
      <el-table-column label="RTMPS" align="center" prop="rtmpSslPort" width="70" />
      <el-table-column label="RTP代理" align="center" prop="rtpProxyPort" width="80" />
      <el-table-column label="RTSP" align="center" prop="rtspPort" width="70" />
      <el-table-column label="RTSPS" align="center" prop="rtspSslPort" width="70" />
      <el-table-column label="FLV" align="center" prop="flvPort" width="70" />
      <el-table-column label="FLVS" align="center" prop="flvSslPort" width="70" />
      <el-table-column label="WS-FLV" align="center" prop="wsFlvPort" width="80" />
      <el-table-column label="WSS-FLV" align="center" prop="wsFlvSslPort" width="80" />
      <el-table-column label="自动配置" align="center" prop="autoConfig" width="90">
        <template slot-scope="scope">
          <el-tag :type="scope.row.autoConfig == 1 ? 'success' : 'info'" size="mini">
            {{ scope.row.autoConfig == 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="密钥" align="center" prop="secret" width="100" show-overflow-tooltip />
      <el-table-column label="类型" align="center" prop="type" width="80" />
      <el-table-column label="启用RTP" align="center" prop="rtpEnable" width="90">
        <template slot-scope="scope">
          <el-tag :type="scope.row.rtpEnable == 1 ? 'success' : 'info'" size="mini">
            {{ scope.row.rtpEnable == 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="RTP端口范围" align="center" prop="rtpPortRange" width="120" show-overflow-tooltip />
      <el-table-column label="发送RTP范围" align="center" prop="sendRtpPortRange" width="120" show-overflow-tooltip />
      <el-table-column label="录像辅助" align="center" prop="recordAssistPort" width="90" />
      <el-table-column label="默认服务器" align="center" prop="defaultServer" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.defaultServer == 1 ? 'success' : 'info'" size="mini">
            {{ scope.row.defaultServer == 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="存活间隔" align="center" prop="hookAliveInterval" width="90" />
      <el-table-column label="录像路径" align="center" prop="recordPath" width="150" show-overflow-tooltip />
      <el-table-column label="保存天数" align="center" prop="recordDay" width="90" />
      <el-table-column label="转码后缀" align="center" prop="transcodeSuffix" width="90" show-overflow-tooltip />
      <el-table-column label="服务器ID" align="center" prop="serverId" width="100" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'" size="mini">
            {{ scope.row.status == 1 ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-dropdown @command="(command) => handlePlayCommand(command, scope.row)" v-hasPermi="['system:wvpMediaServer:play']">
            <el-button size="mini" type="success" icon="el-icon-video-play">
              播放<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="play">快速播放(推荐)</el-dropdown-item>
              <el-dropdown-item divided command="ws_flv">WS-FLV流</el-dropdown-item>
              <el-dropdown-item command="flv">HTTP-FLV流</el-dropdown-item>
              <el-dropdown-item command="rtmp">RTMP流</el-dropdown-item>
              <el-dropdown-item command="hls">HLS流</el-dropdown-item>
              <el-dropdown-item command="rtsp">RTSP流</el-dropdown-item>
              <el-dropdown-item divided command="select">选择流类型</el-dropdown-item>
              <el-dropdown-item command="custom">自定义流地址</el-dropdown-item>
              <el-dropdown-item command="test">播放测试流</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:wvpMediaServer:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:wvpMediaServer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改流媒体服务器配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs>
          <el-tab-pane label="基础配置" name="basic">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="IP地址" prop="ip">
                  <el-input v-model="form.ip" placeholder="请输入IP地址" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="域名" prop="domain">
                  <el-input v-model="form.domain" placeholder="请输入域名" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="服务器ID" prop="serverId">
                  <el-input v-model="form.serverId" placeholder="请输入服务器ID" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="钩子IP" prop="hookIp">
                  <el-input v-model="form.hookIp" placeholder="请输入钩子IP" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="SDP IP" prop="sdpIp">
                  <el-input v-model="form.sdpIp" placeholder="请输入SDP IP" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="流媒体IP" prop="streamIp">
                  <el-input v-model="form.streamIp" placeholder="请输入流媒体IP" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="密钥" prop="secret">
                  <el-input v-model="form.secret" placeholder="请输入密钥" type="password" show-password />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="自动配置" prop="autoConfig">
                  <el-switch v-model="form.autoConfig" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="默认服务器" prop="defaultServer">
                  <el-switch v-model="form.defaultServer" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="端口配置" name="ports">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="HTTP端口" prop="httpPort">
                  <el-input-number v-model="form.httpPort" :min="1" :max="65535" placeholder="HTTP端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="HTTPS端口" prop="httpSslPort">
                  <el-input-number v-model="form.httpSslPort" :min="1" :max="65535" placeholder="HTTPS端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="RTMP端口" prop="rtmpPort">
                  <el-input-number v-model="form.rtmpPort" :min="1" :max="65535" placeholder="RTMP端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="RTMPS端口" prop="rtmpSslPort">
                  <el-input-number v-model="form.rtmpSslPort" :min="1" :max="65535" placeholder="RTMPS端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="RTSP端口" prop="rtspPort">
                  <el-input-number v-model="form.rtspPort" :min="1" :max="65535" placeholder="RTSP端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="RTSPS端口" prop="rtspSslPort">
                  <el-input-number v-model="form.rtspSslPort" :min="1" :max="65535" placeholder="RTSPS端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="FLV端口" prop="flvPort">
                  <el-input-number v-model="form.flvPort" :min="1" :max="65535" placeholder="FLV端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="FLVS端口" prop="flvSslPort">
                  <el-input-number v-model="form.flvSslPort" :min="1" :max="65535" placeholder="FLVS端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="WS-FLV端口" prop="wsFlvPort">
                  <el-input-number v-model="form.wsFlvPort" :min="1" :max="65535" placeholder="WS-FLV端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="WSS-FLV端口" prop="wsFlvSslPort">
                  <el-input-number v-model="form.wsFlvSslPort" :min="1" :max="65535" placeholder="WSS-FLV端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="RTP代理端口" prop="rtpProxyPort">
                  <el-input-number v-model="form.rtpProxyPort" :min="1" :max="65535" placeholder="RTP代理端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="录像辅助端口" prop="recordAssistPort">
                  <el-input-number v-model="form.recordAssistPort" :min="1" :max="65535" placeholder="录像辅助端口" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="RTP配置" name="rtp">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="启用RTP" prop="rtpEnable">
                  <el-switch v-model="form.rtpEnable" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="存活间隔(秒)" prop="hookAliveInterval">
                  <el-input-number v-model="form.hookAliveInterval" :min="1" placeholder="存活间隔" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="RTP端口范围" prop="rtpPortRange">
                  <el-input v-model="form.rtpPortRange" placeholder="例如: 30000-30100" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发送RTP端口范围" prop="sendRtpPortRange">
                  <el-input v-model="form.sendRtpPortRange" placeholder="例如: 30100-30200" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="录像配置" name="record">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="录像路径" prop="recordPath">
                  <el-input v-model="form.recordPath" placeholder="请输入录像存储路径" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="保存天数" prop="recordDay">
                  <el-input-number v-model="form.recordDay" :min="1" placeholder="保存天数" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="转码后缀" prop="transcodeSuffix">
                  <el-input v-model="form.transcodeSuffix" placeholder="例如: .mp4" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 自定义流地址输入对话框 -->
    <el-dialog title="自定义流地址" :visible.sync="customStreamDialog" width="600px" append-to-body>
      <el-form ref="customStreamForm" :model="customStreamForm" label-width="120px">
        <el-form-item label="流地址类型">
          <el-radio-group v-model="customStreamForm.type">
            <el-radio label="ws_flv">WebSocket FLV</el-radio>
            <el-radio label="flv">HTTP FLV</el-radio>
            <el-radio label="rtmp">RTMP</el-radio>
            <el-radio label="hls">HLS</el-radio>
            <el-radio label="rtsp">RTSP</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自定义地址" prop="url">
          <el-input 
            v-model="customStreamForm.url" 
            placeholder="请输入完整的流地址"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="常用地址">
          <el-select v-model="customStreamForm.url" placeholder="选择常用地址" style="width: 100%">
            <el-option 
              v-for="preset in streamPresets" 
              :key="preset.value" 
              :label="preset.label" 
              :value="preset.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="customStreamDialog = false">取 消</el-button>
        <el-button type="primary" @click="playCustomStreamFromDialog">播 放</el-button>
      </div>
    </el-dialog>

    <!-- 视频播放器组件 -->
    <devicePlayer ref="devicePlayer" />
  </div>
</template>

<script>
import { listWvpMediaServer, getWvpMediaServer, delWvpMediaServer, addWvpMediaServer, updateWvpMediaServer } from "@/api/system/wvpMediaServer";
import { wvpLogin } from "@/utils/wvpRequest";
import devicePlayer from "@/components/DevicePlayer";

export default {
  name: "WvpMediaServer",
  components: {
    devicePlayer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // WVP相关状态
      wvpAccessToken: null,
      isWvpLoggedIn: false,
      // 自定义流对话框
      customStreamDialog: false,
      currentPlayingRow: null,
      customStreamForm: {
        type: 'ws_flv',
        url: ''
      },
      // 常用流地址预设
      streamPresets: [
        {
          label: 'RTSP测试流 - Big Buck Bunny',
          value: 'rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov'
        },
        {
          label: 'HLS测试流 - Apple示例',
          value: 'https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/.m3u8'
        },
        {
          label: 'HTTP-FLV本地测试',
          value: 'http://localhost:9080/live/test.flv'
        },
        {
          label: 'WebSocket-FLV本地测试',
          value: 'ws://localhost:9080/live/test.flv'
        },
        {
          label: 'RTMP推流地址示例',
          value: 'rtmp://localhost:1935/live/test'
        }
      ],
      // 流媒体服务器配置表格数据
      wvpMediaServerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ip: null,
        domain: null,
        hookIp: null,
        sdpIp: null,
        streamIp: null,
        httpPort: null,
        httpSslPort: null,
        rtmpPort: null,
        rtmpSslPort: null,
        rtpProxyPort: null,
        rtspPort: null,
        rtspSslPort: null,
        flvPort: null,
        flvSslPort: null,
        wsFlvPort: null,
        wsFlvSslPort: null,
        autoConfig: null,
        secret: null,
        type: null,
        rtpEnable: null,
        rtpPortRange: null,
        sendRtpPortRange: null,
        recordAssistPort: null,
        defaultServer: null,
        hookAliveInterval: null,
        recordPath: null,
        recordDay: null,
        transcodeSuffix: null,
        serverId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.loginToWvp();
  },
  methods: {
    /** 自动登录WVP平台 */
    loginToWvp() {
      if (this.isWvpLoggedIn) return;
      console.log("WVP媒体服务器页面：尝试自动登录WVP平台...");
      wvpLogin('admin', '6f1db4f72b187835d9ac5068223ad822')
        .then(res => {
          if (res.data && res.data.accessToken) {
            this.wvpAccessToken = res.data.accessToken;
            this.isWvpLoggedIn = true;
            console.log("WVP媒体服务器页面：WVP-GB28181-Pro 自动登录成功");
            this.$message.success("WVP平台连接成功");
          } else {
            throw new Error(res.msg || "登录失败，未获取到访问令牌");
          }
        })
        .catch(err => {
          console.error("WVP媒体服务器页面：WVP自动登录错误:", err);
          this.$message.error("WVP平台连接失败: " + (err.message || "未知错误"));
        });
    },
    /** 查询流媒体服务器配置列表 */
    getList() {
      this.loading = true;
      listWvpMediaServer(this.queryParams).then(response => {
        this.wvpMediaServerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ip: null,
        domain: null,
        hookIp: null,
        sdpIp: null,
        streamIp: null,
        httpPort: null,
        httpSslPort: null,
        rtmpPort: null,
        rtmpSslPort: null,
        rtpProxyPort: null,
        rtspPort: null,
        rtspSslPort: null,
        flvPort: null,
        flvSslPort: null,
        wsFlvPort: null,
        wsFlvSslPort: null,
        autoConfig: null,
        secret: null,
        type: null,
        rtpEnable: null,
        rtpPortRange: null,
        sendRtpPortRange: null,
        recordAssistPort: null,
        defaultServer: null,
        createTime: null,
        updateTime: null,
        hookAliveInterval: null,
        recordPath: null,
        recordDay: null,
        transcodeSuffix: null,
        serverId: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加流媒体服务器配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWvpMediaServer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改流媒体服务器配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWvpMediaServer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWvpMediaServer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除流媒体服务器配置编号为"' + ids + '"的数据项？').then(function() {
        return delWvpMediaServer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/wvpMediaServer/export', {
        ...this.queryParams
      }, `wvpMediaServer_${new Date().getTime()}.xlsx`)
    },
    /** 处理播放下拉菜单命令 */
    handlePlayCommand(command, row) {
      switch (command) {
        case 'play':
          this.handlePlay(row);
          break;
        case 'ws_flv':
          this.playStreamByType(row, 'ws_flv');
          break;
        case 'flv':
          this.playStreamByType(row, 'flv');
          break;
        case 'rtmp':
          this.playStreamByType(row, 'rtmp');
          break;
        case 'hls':
          this.playStreamByType(row, 'hls');
          break;
        case 'rtsp':
          this.playStreamByType(row, 'rtsp');
          break;
        case 'select':
          this.showStreamTypeDialog(row);
          break;
        case 'custom':
          this.showCustomStreamDialog(row);
          break;
        case 'test':
          this.playTestStream(row);
          break;
        default:
          this.handlePlay(row);
      }
    },

    /** 播放视频按钮操作 */
    handlePlay(row) {
      try {
        console.log("播放媒体服务器视频:", row);
        
        // 构建完整的流地址配置
        const baseStreamId = `mediaserver_${row.serverId || row.id}_test`;
        const streamInfo = {
          app: "rtp",
          stream: baseStreamId,
          // WebSocket FLV流（推荐）
          ws_flv: `ws://${row.ip}:${row.wsFlvPort || 9080}/rtp/${baseStreamId}.live.flv?originTypeStr=mediaserver`,
          // HTTPS WebSocket FLV流（安全连接）
          wss_flv: `wss://${row.ip}:${row.wsFlvSslPort || 443}/rtp/${baseStreamId}.live.flv?originTypeStr=mediaserver`,
          // HTTP FLV流
          flv: `http://${row.ip}:${row.httpPort || 9080}/rtp/${baseStreamId}.live.flv?originTypeStr=mediaserver`,
          // HTTPS FLV流
          https_flv: `https://${row.ip}:${row.httpSslPort || 443}/rtp/${baseStreamId}.live.flv?originTypeStr=mediaserver`,
          // RTMP流
          rtmp: `rtmp://${row.ip}:${row.rtmpPort || 1935}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          // RTMPS流
          rtmps: `rtmps://${row.ip}:${row.rtmpSslPort || 443}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          // HLS流
          hls: `http://${row.ip}:${row.httpPort || 9080}/rtp/${baseStreamId}/hls.m3u8?originTypeStr=mediaserver`,
          // HTTPS HLS流
          https_hls: `https://${row.ip}:${row.httpSslPort || 443}/rtp/${baseStreamId}/hls.m3u8?originTypeStr=mediaserver`,
          // RTSP流
          rtsp: `rtsp://${row.ip}:${row.rtspPort || 554}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          // RTSPS流
          rtsps: `rtsps://${row.ip}:${row.rtspSslPort || 322}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          // FMP4流
          fmp4: `http://${row.ip}:${row.httpPort || 9080}/rtp/${baseStreamId}.live.mp4?originTypeStr=mediaserver`,
          ws_fmp4: `ws://${row.ip}:${row.wsFlvPort || 9080}/rtp/${baseStreamId}.live.mp4?originTypeStr=mediaserver`,
          // WebRTC流
          rtc: `webrtc://${row.ip}:${row.httpPort || 9080}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          rtcs: `webrtcs://${row.ip}:${row.httpSslPort || 443}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          // 媒体服务器信息
          mediaServerId: row.serverId,
          serverIp: row.ip,
          serverName: row.serverId || `MediaServer-${row.id}`
        };
        
        console.log("完整播放流信息:", streamInfo);
        
        // 打开播放器弹窗
        this.$refs.devicePlayer.openDialog('media', row.id, streamInfo, true);
        console.log("媒体服务器视频播放器弹窗已打开");
        
      } catch (error) {
        console.error("播放错误:", error);
        this.$message.error("播放失败: " + (error.message || "未知错误"));
      }
    },

    /** 显示流类型选择对话框 */
    showStreamTypeDialog(row) {
      this.$confirm('请选择流类型', '播放视频', {
        confirmButtonText: 'WS-FLV流(推荐)',
        cancelButtonText: 'RTMP流',
        type: 'info',
        center: true,
        distinguishCancelAndClose: true,
        showClose: true,
        closeOnClickModal: false
      }).then(() => {
        // 用户选择了WS-FLV流
        this.playStreamByType(row, 'ws_flv');
      }).catch((action) => {
        if (action === 'cancel') {
          // 用户选择了RTMP流
          this.playStreamByType(row, 'rtmp');
        }
      });
    },
    
    /** 根据流类型播放 */
    playStreamByType(row, streamType) {
      try {
        const baseStreamId = `mediaserver_${row.serverId || row.id}_${streamType}`;
        
        // 流地址映射
        const streamUrls = {
          ws_flv: `ws://${row.ip}:${row.wsFlvPort || 9080}/rtp/${baseStreamId}.live.flv?originTypeStr=mediaserver`,
          wss_flv: `wss://${row.ip}:${row.wsFlvSslPort || 443}/rtp/${baseStreamId}.live.flv?originTypeStr=mediaserver`,
          flv: `http://${row.ip}:${row.httpPort || 9080}/rtp/${baseStreamId}.live.flv?originTypeStr=mediaserver`,
          https_flv: `https://${row.ip}:${row.httpSslPort || 443}/rtp/${baseStreamId}.live.flv?originTypeStr=mediaserver`,
          rtmp: `rtmp://${row.ip}:${row.rtmpPort || 1935}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          rtmps: `rtmps://${row.ip}:${row.rtmpSslPort || 443}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          hls: `http://${row.ip}:${row.httpPort || 9080}/rtp/${baseStreamId}/hls.m3u8?originTypeStr=mediaserver`,
          https_hls: `https://${row.ip}:${row.httpSslPort || 443}/rtp/${baseStreamId}/hls.m3u8?originTypeStr=mediaserver`,
          rtsp: `rtsp://${row.ip}:${row.rtspPort || 554}/rtp/${baseStreamId}?originTypeStr=mediaserver`,
          rtsps: `rtsps://${row.ip}:${row.rtspSslPort || 322}/rtp/${baseStreamId}?originTypeStr=mediaserver`
        };
        
        // 构造流信息对象
        let streamInfo = {
          app: "rtp",
          stream: baseStreamId,
          mediaServerId: row.serverId,
          serverIp: row.ip,
          preferredType: streamType
        };
        
        // 添加所有流地址
        for (const [key, url] of Object.entries(streamUrls)) {
          streamInfo[key] = url;
        }
        
        console.log(`播放${streamType}流:`, streamInfo[streamType]);
        
        // 打开播放器对话框
        this.$refs.devicePlayer.openDialog('media', row.id, streamInfo, true);
        
      } catch (error) {
        console.error("播放错误:", error);
        this.$message.error("播放失败: " + (error.message || "未知错误"));
      }
    },
    
    /** 播放自定义流 */
    playCustomStream(row, customUrl) {
      try {
        console.log("播放自定义流:", customUrl);
        
        // 根据URL类型确定流信息
        let streamInfo = {
          app: "custom",
          stream: `custom_${row.id}`,
          mediaServerId: row.serverId,
          serverIp: row.ip
        };
        
        if (customUrl.startsWith('http') && customUrl.includes('.flv')) {
          streamInfo.flv = customUrl;
        } else if (customUrl.startsWith('https') && customUrl.includes('.flv')) {
          streamInfo.https_flv = customUrl;
        } else if (customUrl.startsWith('ws') && customUrl.includes('.flv')) {
          streamInfo.ws_flv = customUrl;
        } else if (customUrl.startsWith('wss') && customUrl.includes('.flv')) {
          streamInfo.wss_flv = customUrl;
        } else if (customUrl.startsWith('rtmp')) {
          streamInfo.rtmp = customUrl;
        } else if (customUrl.startsWith('rtsp')) {
          streamInfo.rtsp = customUrl;
        } else if (customUrl.includes('.m3u8')) {
          streamInfo.hls = customUrl;
        }
        
        // 打开播放器对话框
        this.$refs.devicePlayer.openDialog('media', row.id, streamInfo, true);
        
      } catch (error) {
        console.error("播放错误:", error);
        this.$message.error("播放失败: " + (error.message || "未知错误"));
      }
    },
    
    /** 播放测试流 */
    playTestStream(row, preferredType) {
      // 直接调用播放流类型方法
      this.playStreamByType(row, preferredType || 'ws_flv');
    },

    /** 显示自定义流地址对话框 */
    showCustomStreamDialog(row) {
      this.currentPlayingRow = row;
      this.customStreamForm = {
        type: 'ws_flv',
        url: ''
      };
      this.customStreamDialog = true;
    },

    /** 从对话框播放自定义流 */
    playCustomStreamFromDialog() {
      if (!this.customStreamForm.url) {
        this.$message.warning('请输入流地址');
        return;
      }
      
      if (!this.currentPlayingRow) {
        this.$message.error('播放行信息丢失，请重新选择');
        this.customStreamDialog = false;
        return;
      }

      try {
        this.playCustomStream(this.currentPlayingRow, this.customStreamForm.url);
        this.customStreamDialog = false;
      } catch (error) {
        console.error("自定义流播放错误:", error);
        this.$message.error("播放失败: " + (error.message || "未知错误"));
      }
    }
  }
};
</script>

